package ru.amse.baltijsky.javascheme.nodeshape;

import ru.amse.baltijsky.javascheme.util.Size;
import ru.amse.baltijsky.javascheme.util.VisConst;

import java.awt.*;

/**
 * Represents an isosceles trapezoid shape with double side lines for a DoWhile node housing the code frame.
 * _______________
 * \\          //
 * \\        //
 * ----------
 */
public class DoWhileClosingNodeShape extends AbstractNodeShape {
    /**
     * Main angle (between the side and the base).
     */
    private static final double ALPHA = Math.PI / 2 * (1. - 1. / 5.);
    /**
     * Distance (on the x-axis) between the two parallel segments on each of the sides.
     */
    private static final int SIDE_DIST = 3;
    /**
     * The offset for the code frame inside the central rectangular part.
     */
    private static final Size OFFSET = new Size(5, 5);

    /**
     * Creates a new shape for While node that contains the specified code.
     *
     * @param code the node code
     */
    public DoWhileClosingNodeShape(String code) {
        super(code);
    }

    public void draw(int x, int y, Graphics g) {
        Size size = getBoundRectSize(g);
        int halfX = size.x / 2;
        int halfY = -size.y / 2;
        int ear = (int) (size.y / Math.tan(ALPHA));
        Color oldColor = g.getColor();

        // draw the trapezoid
        g.setColor(VisConst.SCHEME_COL);
        g.drawLine(x - halfX, y + halfY, x + halfX, y + halfY);
        g.drawLine(x - halfX, y + halfY, x - halfX + ear, y - halfY);
        g.drawLine(x - halfX + SIDE_DIST, y + halfY, x - halfX + ear + SIDE_DIST, y - halfY);
        g.drawLine(x - halfX + ear, y - halfY, x + halfX - ear, y - halfY);
        g.drawLine(x + halfX - ear, y - halfY, x + halfX, y + halfY);
        g.drawLine(x + halfX - ear - SIDE_DIST, y - halfY, x + halfX - SIDE_DIST, y + halfY);

        // draw the tail to the subtree
        g.drawLine(x + halfX - ear / 2, y, x + halfX, y);

        // draw label
        g.setColor(VisConst.TEXT_COL);
        g.drawString(getCode(), x - halfX + ear + SIDE_DIST + OFFSET.x, y + OFFSET.y);

        g.setColor(oldColor);
    }

    public Size getBoundRectSize(Graphics g) {
        Size codeSize = getCodeSize(g);
        int basicSizeX = OFFSET.x + codeSize.x + OFFSET.x;
        int basicSizeY = OFFSET.y + codeSize.y + OFFSET.y;
        int sizeX = (int) (basicSizeX + 2 * basicSizeY / Math.tan(ALPHA) + 2 * SIDE_DIST);

        return new Size(sizeX, basicSizeY);
    }
}